package com.huiminpay.transaction.mq;

import com.alibaba.fastjson.JSON;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.service.IAlipaytAgentService;
import com.huiminpay.test.rocketmq.modle.OrderExt;
import com.huiminpay.transaction.api.dto.OrderResultDTO;
import com.huiminpay.transaction.api.dto.PayChannelParamDTO;
import com.huiminpay.transaction.api.dto.PayOrderMqDTO;
import com.huiminpay.transaction.api.service.IPlatformChannelService;
import com.huiminpay.transaction.api.service.ITransactionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @ClassName : OrderListenerMq
 * @Author : 阿泽
 * @Date: 2021/8/18 14:18
 * @Description :
 */
@Component
@RocketMQMessageListener(topic = MqConst.PAY_ORDER_LISTENER,consumerGroup = "pay-consumer-group")
@Slf4j
public class OrderListenerMq implements RocketMQListener<MessageExt> {
    @Reference
    ITransactionService transactionService;
    @Reference
    IAlipaytAgentService alipayAgentservice;
    @Reference
    IPlatformChannelService plateFormChannelService;
    @Override
    public void onMessage(MessageExt messageExt) {
        System.out.println(LocalDateTime.now());
        System.out.println("收到消息["+messageExt+"]");

        byte[] body = messageExt.getBody(); // 获取消息的内容
        String cnt = new String(body);
        System.out.println(cnt);

        PayOrderMqDTO payOrderMqDTO = JSON.parseObject(cnt, PayOrderMqDTO.class);
        String outTradeNo = payOrderMqDTO.getOutTradeNO();
        // 1. 查询自建系统订单信息
        OrderResultDTO orderResultDTO = transactionService.selectPayOrder(outTradeNo);
        if(orderResultDTO.getTradeState().equals("2")
                ||orderResultDTO.getTradeState().equals("3")){
            log.info("【当前订单已支付:{}】",cnt);
            return;
        }
        // 2. 判断支付类型
        PayChannelParamDTO payChannelParamDTO =
                plateFormChannelService.queryParamByAppPlatformAndPayChannel(orderResultDTO.getAppId(),orderResultDTO.getChannel(),
                        orderResultDTO.getPayChannel());
        String param = payChannelParamDTO.getParam();


        String payChannel = payOrderMqDTO.getPayChannell();
        if(payChannel.equals("ALIPAY_WAP")){
            // 使用支付宝
        int reconsumeTimes = messageExt.getReconsumeTimes(); // 获取重试的次数
        if(reconsumeTimes>=8){
            log.info("【当前监听结束:{}】",cnt);
            return;
        }
        throw new RuntimeException("消费重试！第"+reconsumeTimes+"次");



        }

    }
}
